<template>
  <div>
    <a-card>
      <a-button type="primary" @click="showModal"> <PlusOutlined style="color: #ffff" />新建</a-button>
      <!-- 新建弹框 -->
      <a-modal v-model:visible="isModalVisible" title="新建" @ok="handleOk()" @visibleChange="handleModalVisibleChange" style="width: 600px">
        <a-form :model="formState" :rules="rules" ref="formRef"  :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
          <a-form-item ref="name" label="模型名称:" name="name">
            <a-input v-model:value="formState.name" placeholder="请填写模型名称" />
          </a-form-item>
          <a-form-item label="模型描述:" name="dec">
            <a-textarea v-model:value="formState.dec" />
          </a-form-item>
          <a-form-item label="组态模型:" name="description">
            <a-select v-model:value="formState.description" placeholder="请选择组态模型" @change="fetchDeviceModels">
              <a-select-option v-for="item in configurationlist" :key="item.displayUid" :value="item.displayUid">{{
                item.description
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="组态展示页面:" name="PageName">
            <a-select v-model:value="formState.PageName" placeholder="请选择组态展示页面">
              <a-select-option v-for="item in peviceModelslist" :key="item.index" :value="item.PageId">{{ item.PageName }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 编辑弹框 -->
      <a-modal v-model:visible="iseditModalVisible" title="编辑" @ok="editandleOk()" @visibleChange="handleModalVisibleChange" style="width: 600px">
        <a-form :model="formState" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" ref="formRef" >
          <a-form-item ref="name" label="模型名称:" name="name">
            <a-input v-model:value="formState.name" />
          </a-form-item>
          <a-form-item label="模型描述:" name="dec">
            <a-textarea v-model:value="formState.dec" />
          </a-form-item>
          <a-form-item label="组态模型:" name="description">
            <a-select v-model:value="formState.description" placeholder="请选择组态模型" @change="fetchDeviceModels">
              <a-select-option v-for="item in configurationlist" :key="item.displayUid" :value="item.displayUid">{{
                item.description
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="组态展示页面:" name="PageName">
            <a-select v-model:value="formState.PageName" placeholder="请选择组态展示页面">
              <a-select-option v-for="item in peviceModelslist" :key="item.index" :value="item.PageId">{{ item.PageName }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="下发格式:" name="MqttSetDataFormat">
            <div class="main">
              <code-mirror v-model="formState.MqttSetDataFormat" basic :lang="lang" style="height: 280px" :extensions="extensions" />
            </div>
          </a-form-item>
        </a-form>
      </a-modal>
      <a-button style="margin-left: 10px" @click="Refresh"> <UndoOutlined />刷新</a-button>
      <a-table :dataSource="dataSources" :columns="columns" bordered style="margin-top: 5px" :custom-row="() => ({ style: { height: '35px' } })">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-button type="link" @click="EditbulletFrame(record)"><FormOutlined />编辑</a-button>
            <a-button type="link" style="color: #ffa128" @click="GoToDatalist(record)"><UploadOutlined style="color: #ffa128" />数据列表</a-button>
            <a-popconfirm
              title="删除"
              ok-text="确认"
              cancel-text="取消"
              description="你确定要删除吗?"
              @confirm="handleDelete(record)"
              @cancel="cancel"
            >
              <a-button type="link" danger> <DeleteOutlined style="color: red" />删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>
<script setup>
  import { ref, onMounted, reactive } from 'vue';
  import { message } from 'ant-design-vue';
  import CodeMirror from 'vue-codemirror6';
  import { oneDark } from '@codemirror/theme-one-dark';
  import { json } from '@codemirror/lang-json';
  import { MqttEquipmentApi } from '/@/api/system/MqttEquipment.js';
  import { useRouter } from 'vue-router';
  const router = useRouter();
  // 数据列表跳转页面方法
  const GoToDatalist = (record) => {
    router.push({
      path: '/system/MqttEquipMent/MqttListdata',
      query: { muid: record.uuid }, // 查询参数
    });
  };

  //   下拉格式内容
  const initJson = {};
  // 初始化
  let codeVal = ref('');
  // 转成json字符串并格式化
  codeVal.value = JSON.stringify(initJson, null, '\t');
  // json语言
  const lang = json();
  // 扩展
  const extensions = [oneDark];
  // 弹框下拉格式
  const theme = {
    ' &': {
      color: 'white',
      backgroundcolor: '#034',
    },
    'cm-content': {
      caretColor: '#0e9',
    },

    '&.cm-focused .cm-cursor': {
      borderLeftcolor: '#0e9',
    },

    '&.cm-focused .cm-selectionBackground, ::selection': {
      backgroundcolor: '#074',
    },
    '.cm - gutters': {
      backgroundcolor: '#045',
      color: '#ddd',
      border: 'none',
    },
  };
  // 表格列配置
  const columns = ref([
    {
      title: '序号',
      dataIndex: 'ID',
      key: 'ID',
    },
    {
      title: '模型名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '模型描述',
      dataIndex: 'dec',
      key: 'dec',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 320,
    },
  ]);
  //   列表数据
  const dataSources = ref([]);
  async function mqttModelList(val) {
    const parms = {
      type: 20,
    };
    try {
      const res = await MqttEquipmentApi.mqttModelList(parms);
      //   console.log(res);
      dataSources.value = res.list;
    } catch (error) {
      console.error('表格数据出错', error);
    }
  }
  // 刷新按钮
  const Refresh = () => {
    mqttModelList();
    message.success('刷新成功');
  };
  // 组态模型
  const configurationlist = ref([]);
  const selectedDeviceType = ref('');
  const configurationModels = async () => {
    const res = await MqttEquipmentApi.displayModelList();
    // console.log(res);
    if (res && res.list) {
      configurationlist.value = res.list;
    }
  };
  // 组态展示页面
  const peviceModelslist = ref([]);
  const deviceModels = ref([]);
  const fetchDeviceModels = async (val) => {
    const params = {
      muid: val,
    };
    try {
      const res = await MqttEquipmentApi.getDisplayModelLayerData(params);
      if (res && res.layer) {
        peviceModelslist.value = res.layer;
      }
    } catch (error) {
      console.error('出错', error);
    }
  };
  //   编辑弹框
  const iseditModalVisible = ref(false);
  const EditbulletFrame = (record) => {
    configurationModels();
    fetchDeviceModels(record.configUid);
    iseditModalVisible.value = true;
    formState.value = { ...record }; // 填充表单数据
    formState.name = record.name;
    formState.dec = record.dec;
    formState.PageName = record.PageUUID;
    formState.description = record.configUid;
    formState.MqttSetDataFormat = record.MqttSetDataFormat;
    formState.uuid = record.uuid;
  };

  // 新建弹框
  const isModalVisible = ref(false);
  const showModal = () => {
    formState.name = '';
    formState.dec = '';
    formState.PageName = '';
    formState.description = '';
    isModalVisible.value = true;
    configurationModels();
  };
  const formState = reactive({
    name: '', //模型名称
    dec: '', //模型描述
    PageName: '', //组态模型
    description: '', //组态展示页面
    MqttSetDataFormat: '', //下拉格式
  });
  const formRef = ref();
  //   表单校验
  const rules = {
    name: [
      {
        required: true,
        message: '请填写模型名称',
        trigger: 'change',
      },
    ],
    dec: [
      {
        required: true,
        message: '请填写模型描述',
        trigger: 'change',
      },
    ],
    PageName: [
      {
        required: true,
        message: '请选择组态模型描述',
        trigger: 'change',
      },
    ],
    description: [
      {
        required: true,
        message: '请选择组态展示页面',
        trigger: 'change',
      },
    ],
  };
  //   新增确认
  const deviceModelsType = ref('');
  const handleOk = async (val) => {
    try {
      await formRef.value.validate();
      const params = {
        PageUUID: formState.PageName,
        configUid: formState.description,
        name: formState.name,
        dec: formState.dec,
        type: 20,
      };
      const res = await MqttEquipmentApi.mqttModelAdd(params);
      //   console.log(res);
      message.success('新建成功');
      mqttModelList();
      isModalVisible.value = false;
    } catch (error) {
      // 如果校验失败
      console.error('表单验证失败', error);
      message.error('请填写所有必填项');
    }
  };
  // 编辑
  const editandleOk = async (val) => {
    try {
      const parems = {
        data: {
          MqttSetDataFormat: formState.MqttSetDataFormat,
          PageUUID: formState.PageName,
          configUid: formState.description,
          name: formState.name,
          dec: formState.dec,
          type: 20,
        },
        uuid: formState.uuid,
      };
      const res = await MqttEquipmentApi.mqttModelEdit(parems);
      message.success('修改成功');
      mqttModelList();
      iseditModalVisible.value = false;
    } catch (error) {
      console.error('表单修改失败', error);
    }
  };
  // 删除
  async function handleDelete(record) {
    const prams = {
      uuid: record.uuid,
    };
    try {
      const res = await MqttEquipmentApi.mqttModelDel(prams);
      message.success('删除成功');
      mqttModelList();
    } catch (error) {
      console.error('删除失败', error);
    }
  }
  onMounted(() => {
    mqttModelList();
  });
</script>

<style scoped>
  .cm-editor {
    height: 100%;
  }
  .main .cm-editor {
    min-height: 300px;
  }
</style>
